// cloudfunctions/updateCartItem/index.js
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

exports.main = async (event, context) => {
  const { cartItemId, quantity } = event

  if (!cartItemId || !quantity) {
    return {
      success: false,
      message: '参数不完整'
    }
  }

  try {
    // 获取购物车项
    const cartRes = await db.collection('carts').doc(cartItemId).get()
    if (!cartRes.data) {
      return {
        success: false,
        message: '购物车项不存在'
      }
    }

    const cartItem = cartRes.data

    // 获取商品信息
    const productRes = await db.collection('products').doc(cartItem.productId).get()
    if (!productRes.data) {
      return {
        success: false,
        message: '商品不存在'
      }
    }

    // 检查库存
    if (quantity > productRes.data.stock) {
      return {
        success: false,
        message: '库存不足'
      }
    }

    // 更新购物车项数量
    await db.collection('carts').doc(cartItemId).update({
      data: {
        quantity: quantity,
        updatedAt: new Date()
      }
    })

    return {
      success: true
    }

  } catch (err) {
    return {
      success: false,
      message: '更新失败',
      error: err
    }
  }
}
